/*
 * ttrss-reader-fork for Android
 * 
 * Copyright (C) 2010 N. Braden.
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 3 as published by the Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 */

/**
 * 
 */
package org.ttrssreader.widget;

import java.util.ArrayList;
import org.ttrssreader.R;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

/**
 * @author Jean Calixte
 *
 */
public class WidgetConfigureActivity extends Activity implements ListFragmentItemClickListener {
    private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
    ViewPager mViewPager;
    TabsAdapter mTabsAdapter;
    private static final String PREFS_NAME = "org.ttrsseader.widget.WidgetConfigureActivity";
    private static final String PREF_PREFIX_KEY = "ID_";
    public static enum Item_Type {
        TYPE_FEED, TYPE_CAT;
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        
        setResult(RESULT_CANCELED);
        
        if(extras != null)
            mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
        
        if(mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID)
            finish();

        mViewPager = new ViewPager(this);
        mViewPager.setId(R.id.customize_pager);
        setContentView(mViewPager);
        
        final ActionBar bar = getActionBar();
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
        
        mTabsAdapter = new TabsAdapter(this, mViewPager);
        mTabsAdapter.addTab(bar.newTab().setText("Categories"), WidgetCategoryListFragment.class, null);
        mTabsAdapter.addTab(bar.newTab().setText("Feeds"), WidgetFeedListFragment.class, null);
        
        if(savedInstanceState != null)
            bar.setSelectedNavigationItem(savedInstanceState.getInt("tab"));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
    }
    
    public static class TabsAdapter extends FragmentPagerAdapter implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
        private final Context mContext;
        private final ActionBar mActionBar;
        private final ViewPager mViewPager;
        private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
        
        static final class TabInfo {
            private final Class<?> clss;
            private final Bundle args;

            TabInfo(Class<?> _class, Bundle _args) {
                clss = _class;
                args = _args;
            }
        }
        
        public TabsAdapter(Activity activity, ViewPager pager) {
            super(activity.getFragmentManager());
            mContext = activity;
            mActionBar = activity.getActionBar();
            mViewPager = pager;
            mViewPager.setAdapter(this);
            mViewPager.setOnPageChangeListener(this);
        }
        
        public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
            TabInfo info = new TabInfo(clss, args);
            tab.setTag(info);
            tab.setTabListener(this);
            mTabs.add(info);
            mActionBar.addTab(tab);
            notifyDataSetChanged();
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            mActionBar.setSelectedNavigationItem(position);
            
        }

        @Override
        public void onTabReselected(Tab tab, FragmentTransaction ft) {
        }

        @Override
        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            Object tag = tab.getTag();
            for (int i=0; i<mTabs.size(); i++) {
                if (mTabs.get(i) == tag) {
                    mViewPager.setCurrentItem(i);
                }
            }            
        }

        @Override
        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        }

        @Override
        public Fragment getItem(int position) {
            TabInfo info = mTabs.get(position);
            return Fragment.instantiate(mContext, info.clss.getName(), info.args);
        }

        @Override
        public int getCount() {
            return mTabs.size();
        }
        
    }

    @Override
    public void onListFragmentItemClick(Item_Type itemType, int itemId) {
        saveIdPref(this, mAppWidgetId, itemType, itemId);
        AppWidgetManager awm = AppWidgetManager.getInstance(this);
        ComponentName cn = awm.getAppWidgetInfo(mAppWidgetId).provider;
        
        /*if(cn.getClassName().equals("org.ttrssreader.widget.UnreadCountWidget"))
            UnreadCountWidget.update(this, awm, mAppWidgetId);
        else if(cn.getClassName().equals("org.ttrssreader.widget.TickerWidget"))
            TickerWidget.update(this, awm, mAppWidgetId);*/
        
        Intent resultValue = new Intent();
        resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
        setResult(RESULT_OK, resultValue);
        finish();
        
    }
    
    public static void saveIdPref(Context context, int appWidgetId, Item_Type itemType, int itemId) {
        SharedPreferences sp = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor spe = sp.edit();
        spe.putString(PREF_PREFIX_KEY + appWidgetId, itemType + "/" + itemId);
        spe.commit();
    }
    
    public static String loadIdPref(Context context, int appWidgetId) {
        SharedPreferences sp = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        String itemId = sp.getString(PREF_PREFIX_KEY + appWidgetId, null);
        return itemId; 
    }


    public static void deleteTitlePref(Context context, int appWidgetId) {
        SharedPreferences sp = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor spe = sp.edit();
        spe.remove(PREF_PREFIX_KEY + appWidgetId);
        spe.commit();
    }
}
